﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestServer;
using BattleShips.Common;
using System.Data;
using MySql.Data.MySqlClient;
using Finisar.SQLite;

namespace BattleShips.GameServers.CommandRunners {
    class Login : ICommandRunner {

        private SQLiteConnection sql_con;

        private void SetConnection() {
            sql_con = new SQLiteConnection
                ("Data Source=Database.db;Version=3;New=False;Compress=True;");
        }

        public string RunCommand(Command command, GameClient client, GameServer server) {
            List<GameClient> clients = new List<GameClient>();
            clients = server.GetOnlinePlayers();
            string[] userInfo = command.Argument.Split('-');
            string Username = userInfo[0];
            string Password = userInfo[1];

            if (SuccesfullLogin(Username, Password)) {
                client.Username = Username;
                client.IdPlayer = GetUserId(Username, Password);
                client.PlayerStatus = "Idle";
                client.Permission = "NUser";
                client.Presence = "Online";
            } else {
                return "failed:0";
            }
            foreach (var item in clients) {
                if (item.Username.Equals(client.Username) && client.Presence.Equals("Online")) {
                    return "failed:1";
                }
            }
            return "Welcome " + client.Username;

        }

        private bool SuccesfullLogin(string username, string password) {
            SetConnection();
            sql_con.Open();
            string sql = "select * from users";
            SQLiteCommand command = new SQLiteCommand(sql, sql_con);
            SQLiteDataReader reader = command.ExecuteReader();
            while (reader.Read()) {
                if ((username == reader["username"].ToString() && (password == reader["password"].ToString()))) {
                    return true;
                }
            }
            sql_con.Close();
            return false;
        }
        private uint GetUserId(string username, string password) {
            string sql = "select * from users where username=@user AND password=@pass;";
            SQLiteCommand sqlcmd = new SQLiteCommand(sql, sql_con);
            sqlcmd.Parameters.Add("@user", username);
            sqlcmd.Parameters.Add("@pass", password);
            SQLiteDataReader reader = sqlcmd.ExecuteReader();
            while (reader.Read()) {
                return Convert.ToUInt32(reader["id"]);
            }
            return 0;
        }



    }

}
